<template>
  <a-drawer
    :title='title'
    :maskClosable='false'
    :width='drawerWidth'
    placement='right'
    :closable='true'
    @close='handleCancel'
    :visible='visible'
    style='height: 100%;overflow: auto;padding-bottom: 53px;'>

    <template slot='title'>
      <div style='width: 100%;'>
        <span>{{ title }}</span>
        <span style='display:inline-block;width:calc(100% - 51px);padding-right:10px;text-align: right'>
          <a-button @click='toggleScreen' icon='appstore' style='height:20px;width:20px;border:0px'></a-button>
        </span>
      </div>

    </template>

    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>

        <a-form-item label='货品名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-input placeholder='请输入货品名称' v-decorator="[ 'name', validatorRules.name]" />
        </a-form-item>

        <a-form-item label='货物编号' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-input placeholder='请输入货物编号' v-decorator="[ 'partNo', validatorRules.partNo]" :readOnly='!!model.id' />
        </a-form-item>

        <a-form-item label='外部编号' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-input placeholder='请输入外部编号' v-decorator="[ 'outNo', validatorRules.outNo]" />
        </a-form-item>

        <a-form-item label='规格' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-select v-decorator="[ 'specifications', {}]" placeholder='请选择规格'
                    :getPopupContainer='(target) => target.parentNode'>
            <a-select-option :value='1'>件</a-select-option>
            <a-select-option :value='2'>个</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label='产品描述' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-input placeholder='请输入description' v-decorator="[ 'description']" />
        </a-form-item>


        <a-form-item label='库存数量' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-input placeholder='请输入库存数量' v-decorator="[ 'storeSum', validatorRules.storeSum]" />
        </a-form-item>

        <a-form-item label='主机厂项目' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-select
            mode='multiple'
            style='width: 100%'
            :getPopupContainer='(target) => target.parentNode'
            placeholder='请选择主机厂项目'
            optionFilterProp='children'
            v-model='selectedMainEngine'>
            <a-select-option v-for='(e,i) in mainEngineDict' :key='i.toString()' :value='e.mainEngineNo'>
              {{ e.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label='货品类型' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-select
            mode='multiple'
            style='width: 100%'
            :getPopupContainer='(target) => target.parentNode'
            placeholder='请选择货品类型'
            optionFilterProp='children'
            v-model='selectedPartType'>
            <a-select-option v-for='(e,i) in partTypeDict' :key='i.toString()' :value='e.partType'>
              {{ e.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label='应用车型' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-select
            mode='multiple'
            style='width: 100%'
            :getPopupContainer='(target) => target.parentNode'
            placeholder='请选择应用车型'
            optionFilterProp='children'
            v-model='selectedMotorType'>
            <a-select-option v-for='(e,i) in applicationMotorModelDict' :key='i.toString()' :value='e.motorType'>
              {{ e.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label='责任人' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-input placeholder='请输入责任人' v-decorator="[ 'principalName', validatorRules.principalName]" />
        </a-form-item>

        <a-form-item label='上传附件' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <div>
            <a-upload
              list-type='picture'
              :customRequest='imgAdd'
              :remove='imgDel'
              :multiple='false'
              :file-list='fileList'
              @preview='handlePreview'
              @change='handleChange'>
              <div v-if='fileList.length < 9'>
                <a-button>
                  <a-icon type='upload' />
                  upload
                </a-button>
              </div>
            </a-upload>
            <a-modal :visible='previewVisible' :footer='null' @cancel='handleCloseImagePreview'>
              <img alt='example' style='width: 100%' :src='previewImage' />
            </a-modal>
          </div>
        </a-form-item>

      </a-form>
    </a-spin>
    <div class='drawer-bootom-button' v-show='!disableSubmit'>
      <a-popconfirm title='确定放弃编辑？' @confirm='handleCancel' okText='确定' cancelText='取消'>
        <a-button style='margin-right: .8rem'>取消</a-button>
      </a-popconfirm>
      <a-button @click='handleSubmit' type='primary' :loading='confirmLoading'>提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
import pick from 'lodash.pick'
import moment from 'moment'


import {
  getRelsByPartId,
  addMotorPart,
  editMotorPart,
  getApplicationMotorModelDict,
  getMainEngineRelsDict,
  getPartTypeDict,
  uploadFile,
  getUploadedPreviewFiles
} from '@/api/api'

export default {
  name: 'MotorPartModel',
  components: {},
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      selectedMainEngine: [],
      selectedPartType: [],
      selectedMotorType: [],
      partTypeDict: {},
      applicationMotorModelDict: {},
      mainEngineDict: {},
      modalWidth: 800,
      drawerWidth: 700,
      modaltoggleFlag: true,
      confirmDirty: false,
      id: '', //保存货品id
      disableSubmit: false,
      validatorRules: {
        name: {
          rules: [{
            required: true, message: '请输入货品信息!'
          }]
        },
        partNo: { rules: [{ required: true, message: '请输入用户名称!' }] },
        outNo: {
          rules: [
            { required: true, message: '请输入外部编号' },
            { validator: this.validateWorkNo }
          ]
        },
        storeSum: {
          rules: [{ required: true, message: '请输入库存数量' }]
        },
        principalName: {
          rules: [{ require: true, message: '请输入责任人' }]
        }

      },
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this)
    }
  },
  created() {

  },
  methods: {
    imgAdd(data) {
      let formdata = new FormData()
      formdata.append('file', data.file)
      uploadFile(formdata).then(res => {
        if (res.code === 200) { // 上传成功时（自己封装了response）
          data.onSuccess(res.data)
        } else {
          data.onError()
        }
      })
    },
    // 删除图片
    imgDel(file) {
      this.fileList.splice(this.fileList.indexOf(file), 1)
    },
    // 关闭文件预览模态框
    handleCloseImagePreview() {
      this.previewVisible = false
    },
    // 打开模态框（图片预览）
    async handlePreview(file) {
      console.log(file)
      this.previewImage = file.thumbUrl || file.response.downloadUrl
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      this.fileList = fileList
    },
    //窗口最大化切换
    toggleScreen() {
      if (this.modaltoggleFlag) {
        this.modalWidth = window.innerWidth
      } else {
        this.modalWidth = 800
      }
      this.modaltoggleFlag = !this.modaltoggleFlag
    },
    refresh() {
      this.id = ''
      this.selectedMainEngine = []
      this.selectedPartType = []
      this.selectedMotorType = []
    },
    add() {
      this.refresh()
      this.edit({ activitiSync: '1' })
    },
    edit(record) {
      this.resetScreenSize() // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
      let that = this
      that.initialDictList()
      that.form.resetFields()

      //编辑反显
      if (record.hasOwnProperty('id')) {
        that.loadSelectedDicts(record.id)
        that.loadUploadedFiles(record.attaIds)
      }

      that.id = record.id
      that.model = Object.assign({}, record)
      that.visible = true
      that.$nextTick(() => {
        that.form.setFieldsValue(pick(this.model, 'name', 'partNo', 'outNo',
          'specifications', 'description', 'storeSum', 'principalName'))
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.disableSubmit = false
    },
    moment,
    handleSubmit() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)

          //fill selected val
          formData.selectedMotorType = this.selectedMotorType.length > 0 ? this.selectedMotorType.join(',') : ''
          formData.selectedPartType = this.selectedPartType.length > 0 ? this.selectedPartType.join(',') : ''
          formData.selectedMainEngine = this.selectedMainEngine.length > 0 ? this.selectedMainEngine.join(',') : ''

          //fill attaIds
          formData.attaIds = that.fileList.map(o => {
            return o.id || o.response.id
          }).join(',')

          let obj
          if (!this.model.id) {
            //根据id 判断调用添加还是修改
            formData.id = this.id
            obj = addMotorPart(formData)
          } else {
            obj = editMotorPart(formData)
          }
          obj.then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })

        }
      })
    },
    handleCancel() {
      this.close()
    },

    handleConfirmBlur(e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },

    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth
      } else {
        this.drawerWidth = 700
      }
    },
    initialDictList() {
      let _that = this
      getApplicationMotorModelDict().then((res) => {
        this.$nextTick(() => {
          _that.applicationMotorModelDict = res.result
        })
      })
      getPartTypeDict().then((res) => {
        this.$nextTick(() => {
          _that.partTypeDict = res.result
        })

      })
      getMainEngineRelsDict().then((res) => {
        this.$nextTick(() => {
          _that.mainEngineDict = res.result
        })
        console.log('complete')
      })
    },
    loadSelectedDicts(id) {
      getRelsByPartId({ id: id }).then((res) => {
        this.selectedMotorType = res.result.selectedMotorType.split(',')
        this.selectedPartType = res.result.selectedPartType.split(',')
        this.selectedMainEngine = res.result.selectedMainEngine.split(',')
      })
    },
    loadUploadedFiles(attaIds) {
      getUploadedPreviewFiles({ attaIds: attaIds }).then((res) => {
        this.fileList = res.data || []
      })

    }
  }
}
</script>

<style scoped>
.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}

/* tile uploaded pictures */
.upload-list-inline >>> .ant-upload-list-item {
  float: left;
  width: 200px;
  margin-right: 8px;
}

.upload-list-inline >>> .ant-upload-animate-enter {
  animation-name: uploadAnimateInlineIn;
}

.upload-list-inline >>> .ant-upload-animate-leave {
  animation-name: uploadAnimateInlineOut;
}
</style>